package com.bio.service.right.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

import com.bio.dao.right.MenuDao;
import com.bio.dao.right.TypemenuDao;
import com.bio.entity.right.Menu;
import com.bio.entity.right.Typemenu;
import com.bio.service.impl.AbstractService;
import com.bio.service.right.MenuService;
import com.bio.utils.Constants;
import com.bio.utils.Pager;
import com.bio.vo.right.MenuVo;

public class MenuServiceImpl extends AbstractService<Menu, MenuDao> implements MenuService{

	public MenuServiceImpl(MenuDao dao) {
		super(dao);
	}

	private TypemenuDao typemenuDao;
	
	@Override
	public Pager<Menu> findMenusBySuperior(Long superiorId) {
		return dao.findMenusBySuperior(superiorId);
	}

	@Override
	public List<MenuVo> findMenuVosBySuperior(Long superiorId, Long userTypeId) throws IllegalAccessException, InvocationTargetException {
		List<Menu> menus = dao.findMenusBySuperior(superiorId).getResult();
		List<MenuVo> vos = new ArrayList<MenuVo>();
		List<Typemenu> typemenus = typemenuDao.findAllByUsertype(userTypeId);
		for (Menu m : menus){
			List<Menu> secMenus = dao.findMenusBySuperior(m.getId()).getResult();
			List<MenuVo> svos = new ArrayList<MenuVo>();
			for(Menu sm : secMenus){
				MenuVo svo = new MenuVo();
				BeanUtils.copyProperties(svo, sm);
				if(this.isExistRight(sm, typemenus) || Constants.UserType.SUPER_ADMIN.equals(userTypeId) || Constants.UserType.Company_ADMIN.equals(userTypeId)){
					svo.setHaveRight(true);
				}else{
					svo.setHaveRight(false);
				}
				svos.add(svo);
			}
			MenuVo vo = new MenuVo();
			BeanUtils.copyProperties(vo, m);
			vo.setLowerMenus(svos);
			vos.add(vo);
		}
		return vos;
	}

	private boolean isExistRight(Menu menu,List<Typemenu> typemenus){
		for(Typemenu t : typemenus){
			if(t.getMenuId().equals(menu.getId())){
				return true;
			}
		}
        return false;
	}
	
	public void setTypemenuDao(TypemenuDao typemenuDao) {
		this.typemenuDao = typemenuDao;
	}

}
